package controllers

import (
	"simple-crm/models"
	"simple-crm/services"
	"simple-crm/utils"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type PushController struct {
	DB          *gorm.DB
	PushService *services.PushService
}

type ManualPushRequest struct {
	CustomerID uint   `json:"customer_id" binding:"required"`
	PartnerID  uint   `json:"partner_id" binding:"required"`
	Notes      string `json:"notes"`
}

type PushRecordQuery struct {
	Page       int    `form:"page,default=1"`
	Size       int    `form:"size,default=10"`
	CustomerID uint   `form:"customer_id"`
	PartnerID  uint   `form:"partner_id"`
	PushType   string `form:"push_type"`
	Status     string `form:"status"`
	StartDate  string `form:"start_date"`
	EndDate    string `form:"end_date"`
}

// NewPushController 创建推送控制器
func NewPushController(db *gorm.DB, pushService *services.PushService) *PushController {
	return &PushController{
		DB:          db,
		PushService: pushService,
	}
}



// ManualPush 手动推送
func (pc *PushController) ManualPush(c *gin.Context) {
	var req ManualPushRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 查找客户
	var customer models.Customer
	if err := pc.DB.First(&customer, req.CustomerID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "客户不存在")
		} else {
			utils.InternalServerError(c, "查询客户失败")
		}
		return
	}

	// 查找合作机构
	var partner models.Partner
	if err := pc.DB.First(&partner, req.PartnerID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "合作机构不存在")
		} else {
			utils.InternalServerError(c, "查询合作机构失败")
		}
		return
	}

	// 检查客户是否可以推送
	if !customer.CanPush() {
		utils.BadRequest(c, "客户当前状态不允许推送")
		return
	}

	// 检查合作机构是否可以接收推送
	if !partner.CanReceivePush() {
		utils.BadRequest(c, "合作机构当前状态不允许接收推送")
		return
	}

	// 执行手动推送
	result, err := pc.PushService.ManualPushCustomer(customer.ID, partner.ID, userID.(uint), req.Notes)
	if err != nil {
		utils.InternalServerError(c, "手动推送失败: "+err.Error())
		return
	}

	// 记录操作日志
	models.LogCustomerPush(pc.DB, userID.(uint), customer.ID, "手动推送客户: "+customer.Name+" 到 "+partner.Name, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "手动推送成功", gin.H{
		"customer": customer,
		"partner":  partner,
		"result":   result,
	})
}



// GetPushRecords 获取推送记录
func (pc *PushController) GetPushRecords(c *gin.Context) {
	var query PushRecordQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 构建查询
	db := pc.DB.Model(&models.PushRecord{}).Preload("Customer").Preload("Partner").Preload("Pusher")

	// 添加过滤条件
	if query.CustomerID > 0 {
		db = db.Where("customer_id = ?", query.CustomerID)
	}
	if query.PartnerID > 0 {
		db = db.Where("partner_id = ?", query.PartnerID)
	}
	if query.PushType != "" {
		db = db.Where("push_type = ?", query.PushType)
	}
	if query.Status != "" {
		db = db.Where("status = ?", query.Status)
	}
	if query.StartDate != "" {
		db = db.Where("pushed_at >= ?", query.StartDate)
	}
	if query.EndDate != "" {
		db = db.Where("pushed_at <= ?", query.EndDate)
	}

	// 计算总数
	var total int64
	db.Count(&total)

	// 分页查询
	var records []models.PushRecord
	offset := (query.Page - 1) * query.Size
	if err := db.Offset(offset).Limit(query.Size).Order("pushed_at DESC").Find(&records).Error; err != nil {
		utils.InternalServerError(c, "查询推送记录失败")
		return
	}

	// 循环查询关联数据
	for i := range records {
		// 查询客户信息
		if records[i].CustomerID != 0 {
			var customer models.Customer
			if err := pc.DB.First(&customer, records[i].CustomerID).Error; err == nil {
				records[i].Customer = customer
			}
		}

		// 查询合作机构信息
		if records[i].PartnerID != 0 {
			var partner models.Partner
			if err := pc.DB.First(&partner, records[i].PartnerID).Error; err == nil {
				records[i].Partner = partner
			}
		}

		// 查询推送人信息
		if records[i].PushedBy != 0 {
			var pusher models.User
			if err := pc.DB.First(&pusher, records[i].PushedBy).Error; err == nil {
				records[i].Pusher = pusher
			}
		}
	}

	utils.PageSuccess(c, records, total, query.Page, query.Size)
}

// GetPushRecord 获取单个推送记录
func (pc *PushController) GetPushRecord(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "推送记录ID无效")
		return
	}

	var record models.PushRecord
	if err := pc.DB.Preload("Customer").Preload("Partner").Preload("Pusher").First(&record, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "推送记录不存在")
		} else {
			utils.InternalServerError(c, "查询推送记录失败")
		}
		return
	}

	utils.Success(c, record)
}

// RetryPush 重试推送
func (pc *PushController) RetryPush(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "推送记录ID无效")
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 查找推送记录
	var record models.PushRecord
	if err := pc.DB.Preload("Customer").Preload("Partner").First(&record, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "推送记录不存在")
		} else {
			utils.InternalServerError(c, "查询推送记录失败")
		}
		return
	}

	// 检查是否可以重试
	if !record.CanRetry() {
		utils.BadRequest(c, "该推送记录不允许重试")
		return
	}

	// 执行重试
	result, err := pc.PushService.RetryPush(record.ID, userID.(uint))
	if err != nil {
		utils.InternalServerError(c, "重试推送失败: "+err.Error())
		return
	}

	// 记录操作日志
	models.LogCustomerPush(pc.DB, userID.(uint), record.CustomerID, "重试推送: "+record.Customer.Name+" 到 "+record.Partner.Name, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "重试推送成功", result)
}

// GetRecommendedPartners 获取推荐的合作机构
func (pc *PushController) GetRecommendedPartners(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("customer_id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "客户ID无效")
		return
	}

	// 获取推荐的合作机构
	partners, err := pc.PushService.GetRecommendedPartners(uint(id))
	if err != nil {
		utils.InternalServerError(c, "获取推荐合作机构失败: "+err.Error())
		return
	}

	utils.Success(c, partners)
}



// GetPushStats 获取推送统计
func (pc *PushController) GetPushStats(c *gin.Context) {
	stats, err := pc.PushService.GetPushStats()
	if err != nil {
		utils.InternalServerError(c, "获取推送统计失败: "+err.Error())
		return
	}

	utils.Success(c, stats)
}

// IndexPage 推送管理首页
func (pc *PushController) IndexPage(c *gin.Context) {
	c.HTML(200, "push/index.html", gin.H{
		"Title":       "推送管理",
		"CurrentPage": "push",
	})
}

// ManualPushPage 手动推送页面
func (pc *PushController) ManualPushPage(c *gin.Context) {
	c.HTML(200, "push/manual.html", gin.H{
		"Title":       "手动推送",
		"CurrentPage": "push",
	})
}

// RecordsPage 推送记录页面
func (pc *PushController) RecordsPage(c *gin.Context) {
	c.HTML(200, "push/records.html", gin.H{
		"Title":       "推送记录",
		"CurrentPage": "push-records",
	})
}

// StatsPage 推送统计页面
func (pc *PushController) StatsPage(c *gin.Context) {
	c.HTML(200, "push/stats.html", gin.H{
		"Title":       "推送统计",
		"CurrentPage": "push-stats",
	})
}
